/*
 * T.Raynal - A.Aviles - F.Diallo
 * XML-Scenarios
 * PPA AL5-2
 * December 2012 
 */
package trash;

import java.util.ArrayList;
import java.util.List;

import common.exception.TreeBuildingException;

public class BinaryTree<T extends IWeightable<T>> {
	Node<T> root;
	int size = 0;
	int i;
	
	public void add(Node<T> node,T element) throws TreeBuildingException {
	    if (root == null && element != null) {
	        root = new Node<T>(element);
	        size++;
	    } else if (element != null) {
	        root = insert(node, element);
	    }
	}

	private Node<T> insert(Node<T> node, T value) throws TreeBuildingException {
		Node<T> result = new Node<T>(value);

		if (value.getWeight()< node.value.getWeight()) {
		    if (result.left != null) {
		        result.left = insert(result.left, value);
		    } else {
		        result.left = new Node<T>(value);
		        size++;
		    }
		}
		
		else if (value.getWeight()> node.value.getWeight()) {
		    if (result.right != null) {
		        result.right = insert(result.right, value);
		    } else {
		        result.right = new Node<T>(value);
		        size++;
		    }
		}
		
		else
		{
			throw new TreeBuildingException("Should not have similar weight at this point.");
			
		}
		
		return result;
	}
	
	public T get(T key) {
	    if (root == null)
	        return null;

	    Node<T> node = root;
	    int compareResult;
	    while ((compareResult = node.value.compareTo(key)) != 0) {
	        if (compareResult > 0) {
	            if (node.left != null)
	                node = node.left;
	            else
	                return null;
	        } else {
	            if (node.right != null)
	                node = node.right;
	            else
	                return null;
	        }
	    }
	    return node.value;
	}
	
	public List<T> toList() {
	    List<T> result = new ArrayList<T>();
	    treeToList(root, result);
	    return result;
	}
	
	private void treeToList(Node<T> node, List<T> goal) {
	    if (node != null) {
	        treeToList(node.left, goal);
	        goal.add(node.value);
	        treeToList(node.right, goal);
	    }
	}

}
